import axios from './axios-td.js' //请求模块
import base from './base.js' //帮助
import db from './localStorageHelper.js' //帮助
import config from '../config.js'
import wxsdk from 'weixin-js-sdk'; //微信jssdk

function WeChatLogin(_path, _success, _error) {
    var appid = window.localStorage.getItem('appid') || config.defappid;

    var state = GetUrlParam('state');
    if (state != null && state.length > 0) {
        axios.post({
            url: '/api/webapi/Account/WechatLoginStep2',
            data: { appid: appid, stateCode: state, autoLogin: 1 },
            success: (_res) => {
                window.localStorage.setItem('userInfo', JSON.stringify(_res.modelMember))
                typeof _success === "function" && _success(_res.modelMember);

            },
            error: (_res) => {
                typeof _error === "function" && _error(_res);
            }
        })

        return;
    }

    var local = window.location.href + '?{state}';
    if (_path.length > 0) {
        local = config.login + '?state={state}#' + _path
    }

    axios.post({
        url: '/api/webapi/Account/WechatLoginStep1',
        data: { appid: appid, redirectUrl: encodeURIComponent(local) },
        success: (_res) => {
            window.location.href = _res.jumpUrl
        },
        error: (_res) => {
            typeof _error === "function" && _error(_res);
        }
    })
}

function GetUrlParam(_name) {
    var reg = new RegExp('(^|&)' + _name + '=([^&]*)(&|$)');
    var r = window.location.search.substr(1).match(reg);
    if (r != null) {
        return unescape(r[2]);
    }
    return null
}

//请求微信jssdk
function SetWxConfig(_success, _error) {
    axios.post({
        url: '/api/webapi/init/JSSDKGetSign',
        success: (_res) => {
            wxsdk.config({
                debug: false,
                appId: _res.appId,
                timestamp: _res.timestamp,
                nonceStr: _res.nonceStr,
                signature: _res.signature,
                jsApiList: [
                    'chooseWXPay',
                    'getLocation',
                    'openLocation',
                    'updateAppMessageShareData',
                    'updateTimelineShareData',
                    'onMenuShareTimeline',
                    'onMenuShareAppMessage',
                ]
            })

            wxsdk.ready(() => {
                typeof _success === "function" && _success();
            })

            wxsdk.error((_res) => {
                typeof _error === "function" && _error();
                // console.log('初始化失败',_res)
            })
        }
    })
}
//进行微信分享
function Shared(_options) {
    //设置分享链接
    var url = _options.url || '';
    if (url.length <= 0) {
        url = window.location.href
    }
    //获取缓存里的appid
    var appid = window.localStorage.getItem('now-appid') || config.defappid;

    if (appid.length > 0) {
        //拼接来源appid
        var str_before = url.split('#')[0];
        var str_after = url.split('#')[1];
        if (str_before.indexOf('?') >= 0) {
            var str_before = str_before.split('?')[0]
        }
        //获取用户 parentUserId
        var userinfo = window.localStorage.getItem('userInfo');
        if (userinfo && userinfo.length > 0) {
            try {
                userinfo = JSON.parse(userinfo) || null;
            } catch {
                userinfo = null
            }

        }
        
        //获取最后一位字符
        var lastStr=str_before.charAt(str_before.length-1);
        if(lastStr=='/') {
            str_before=str_before.substring(0,str_before.length-1);
        }
        str_before=config.domain;
        if (userinfo && userinfo.memberId!=null && userinfo.memberId!=undefined && userinfo.memberId.length > 0) {

            url = str_before + '?now_appid=' + appid + '&parentUserId=' + userinfo.memberId + '/#' + str_after
        } else {
            url = str_before + '?now_appid=' + appid + '/#' + str_after
        }
    }

    SetWxConfig(() => {
        //调用分享接口
        wxsdk.onMenuShareAppMessage({
            title: _options.title, // 分享标题
            desc: _options.desc, // 分享描述
            link: url, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
            imgUrl: _options.imgUrl, // 分享图标
            success: function() {
                //alert('分享成功')
                // 设置成功
                typeof _options.success === "function" && _options.success()
            }
        })
        wxsdk.onMenuShareTimeline({
            title: _options.title, // 分享标题
            desc: _options.desc, // 分享描述
            link: url, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
            imgUrl: _options.imgUrl, // 分享图标
            success: function() {
                //alert('分享成功')
                // 设置成功
                typeof _options.success === "function" && _options.success()
            }
        })
    })

}
//定位
function GetLocation(_callback) {
    //判断上次获取的时间 1分钟之内不重复获取
    var time = db.get('localtion_time');
    if (!time) {
        SetWxConfig(() => {
            wxsdk.getLocation({
                type: 'gcj02', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
                success: (res) => {
                    //存下定位
                    var latlng = {
                        lat: res.latitude,
                        lng: res.longitude
                    }
                    db.set('localtion_time', latlng, { expires: 60000 })
                    window.localStorage.setItem('latlng', JSON.stringify(latlng));
                    typeof _callback === "function" && _callback();
                },
                error: (_res) => {

                    db.set('localtion_time', 13, { expires: 60000 })
                    typeof _callback === "function" && _callback();
                }
            });
        }, () => {

            typeof _callback === "function" && _callback();
        })
        return;
    }
    typeof _callback === "function" && _callback();
}
//支付
function ChooseWXPay(_options) {
    SetWxConfig(() => {
        wxsdk.chooseWXPay({
            timestamp: _options.timestamp,
            nonceStr: _options.nonceStr,
            package: _options.package,
            signType: _options.signType,
            paySign: _options.paySign,
            success: (_res) => {
                typeof _options.success === "function" && _options.success(_res)
            },
            faio: (_res) => {
                typeof _options.error === "function" && _options.error(_res)
            }
        })
    })


}
//打开地图
function OpenLocation(_options) {
    SetWxConfig(() => {
        wxsdk.openLocation({
            latitude: _options.latitude || 0, // 纬度，浮点数，范围为90 ~ -90
            longitude: _options.longitude || 0, // 经度，浮点数，范围为180 ~ -180。
            name: _options.name || '', // 位置名
            address: _options.address || '', // 地址详情说明
            scale: _options.scale || 15, // 地图缩放级别,整形值,范围从1~28。默认为最大
            infoUrl: _options.link || '' // 在查看位置界面底部显示的超链接,可点击跳转
        })
    })
}

export default {
    WeChatLogin: WeChatLogin,
    GetLocation: GetLocation,
    Shared: Shared,
    ChooseWXPay: ChooseWXPay,
    OpenLocation:OpenLocation
}